import { executeApi } from '../api/conn';
import { Base64 } from 'js-base64';
import { useAnvilCodeStore } from '../store/modules/code';
import { ajax, localAjax, localAjaxByJson } from '@/utils/ajax';
import { searchSequenceValue } from '../api/uni';
import { ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash-es';
import { downloadUrl, randomString } from '@/utils/zmids';
import { uploadApi } from '@code/components/anvil-code-low-common/api/conn';
import jp from 'jsonpath';
import dayjs from 'dayjs';

// 表单提交时对所有date类型的值进行补0
export const fillDateFieldZeros = function (field) {
  const strArr = field.split(' ');
  let left = '0000-00-00';
  let right = '00:00:00';
  if (strArr[0]) {
    const str0 = strArr[0];
    const str0Arr = str0.split('-');
    const len = str0Arr.length;
    if (len < 3) {
      const rest = 3 - len;
      for (let i = 0; i < rest; i++) {
        str0Arr.push('00');
      }
      left = str0Arr.join('-');
    } else {
      left = str0;
    }
  }
  if (strArr[1]) {
    const str1 = strArr[1];
    const str1Arr = str1.split(':');
    const len = str1Arr.length;
    if (len < 3) {
      const rest = 3 - len;
      for (let i = 0; i < rest; i++) {
        str1Arr.push('00');
      }
      right = str1Arr.join(':');
    } else {
      right = str1;
    }
  }
  return left + ' ' + right;
};

// 表单提交时对time类型的值进行补0
export const fillTimeFieldZeros = function (field) {
  // 获取当前年月日
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();

  const strArr = field.split(':');
  let left = `${year}-${month}-${day}`;
  let right = '00:00:00';
  const len = strArr.length;
  if (len < 3) {
    const rest = 3 - len;
    for (let i = 0; i < rest; i++) {
      strArr.push('00');
    }
    right = strArr.join(':');
  } else {
    right = field;
  }
  return left + ' ' + right;
};

// 回显时根据date类型进行删0
export const deleteDateFieldZeros = function (valueFormat, field) {
  const formatArr = valueFormat.split(' ');
  const strArr = field.split(' ');
  let left = '';
  let right = '';
  if (formatArr[0]) {
    const format0 = formatArr[0];
    const str0 = strArr[0];
    const format0Arr = format0.split('-');
    const str0Arr = str0.split('-');

    const len = format0Arr.length;
    const newArr = str0Arr.slice(0, len);
    left = newArr.join('-');
  }
  if (formatArr[1]) {
    const format1 = formatArr[1];
    const str1 = strArr[1];
    const format1Arr = format1.split(':');
    const str1Arr = str1.split(':');

    const len = format1Arr.length;
    const newArr = str1Arr.slice(0, len);
    right = newArr.join(':');
  }
  if (right) {
    return left + ' ' + right;
  } else {
    return left;
  }
};

// 回显时根据time类型进行删0
export const deleteTimeFieldZeros = function (valueFormat, field) {
  let str = '';
  const formatArr = valueFormat.split(':');
  const strArr = field.split(':');

  const len = formatArr.length;
  const newArr = strArr.slice(0, len);
  str = newArr.join(':');

  return str;
};

// 获取表单数据之后对特定的一些组件数据进行转化处理
export const handleFormDataTransBack = function (columns, form) {
  try {
    for (let key in form) {
      const CurCol = columns.find((col) => col.prop === key);
      if (CurCol) {
        const { type, dataType, valueFormat, valueType, children } = CurCol;
        // 处理可能为空值的报错情况
        if (form[key]) {
          // date日期格式都需要根据当前格式转换
          if (type === 'datetime' || type === 'date') {
            form[key] = deleteDateFieldZeros(valueFormat, form[key]);
          } else if (type == 'time') {
            form[key] = deleteTimeFieldZeros(valueFormat, form[key]);
          }
          // 上传组件需要把文件json字符串转换为对象
          else if (type === 'upload') {
            const { listType } = CurCol;
            // 除了头像类型的附件，其他都需要转为数组
            if (listType !== 'picture-img') {
              form[key] = JSON.parse(form[key]);
            }
          }
          // checkbox数组需要从字符串转化为数组形式查看
          // else if (type === "checkbox") {
          //   form[key] = form[key].split(",");
          // }
          // 其他valueType为数组类型的组件，需要从字符串转化为数组查看
          else if (valueType == 'array' && type !== 'dynamic' && type !== 'anvilDynamic') {
            form[key] = JSON.parse(form[key]);
          }
          // 子表单内部数据结构等同一个表单，递归处理数据结构
          else if (type == 'dynamic' || type == 'anvilDynamic') {
            const { column } = children;
            if (column && column.length && form[key].length) {
              for (let index in form[key]) {
                handleFormDataTransBack(column, form[key][index]);
              }
            }
          } else if (type == 'vueQuillEditor') {
            form[key] = JSON.parse(form[key]);
          } else if (type == 'imageUpload') {
            form[key] = JSON.parse(form[key]);
          }
        }
      }
    }
  } catch (err) {
    console.log('handleFormDataTransBackErr', err);
  }
};

// 提交表单数据之前对特定的一些组件数据进行转化处理
export const handleFormDataTrans = function (columns, form) {
  try {
    for (let key in form) {
      const CurCol = columns.find((col) => col.prop === key);
      if (CurCol) {
        const { type, dataType, valueType, children } = CurCol;
        if (form[key]) {
          // 日期格式都需要转换为年月日时分秒格式，缺的需要补0
          if (type === 'datetime' || type === 'date') {
            form[key] = fillDateFieldZeros(form[key]);
          } else if (type == 'time') {
            form[key] = fillTimeFieldZeros(form[key]);
          }
          // 上传组件需要把文件对象转化为json字符串
          else if (type === 'upload') {
            const { listType } = CurCol;
            // 除了头像类型的附件，其他都需要转为数组
            if (listType !== 'picture-img') {
              form[key] = JSON.stringify(form[key]);
            }
          }
          // checkbox数组需要从数组化为字符串形式查看
          // else if (type === "checkbox") {
          //   form[key] = form[key].join(",");
          // }
          // 其他valueType为数组类型的组件，需要从数组转化为字符串提交
          else if (valueType == 'array' && type !== 'dynamic' && type !== 'anvilDynamic') {
            form[key] = JSON.stringify(form[key]);
          }
          // 子表单内部数据结构等同一个表单，递归处理数据结构
          else if (type == 'dynamic' || type == 'anvilDynamic') {
            const { column } = children;
            if (column && column.length && form[key].length) {
              for (let index in form[key]) {
                handleFormDataTrans(column, form[key][index]);
              }
            }
          } else if (type == 'vueQuillEditor') {
            form[key] = JSON.stringify(form[key]);
          } else if (type == 'imageUpload') {
            form[key] = JSON.stringify(form[key]);
          }
        }
      }
    }
  } catch (err) {
    console.log('handleFormDataTransErr', err);
  }
};

// 根据组件类型生成表单校验规则
export const generateFormRules = function (component, data) {
  let pattern = component.pattern ? new RegExp(component.pattern) : '';
  let des = '';
  let type = 'string';
  let required = component.isRequired == 'Y';
  // 禁止输入空格
  const spacePattern = /^(?!\s*$).+/;

  if (component.type == 'phoneNumber') {
    pattern = /^1[3456789]\d{9}$/;
    des = '11位';
  }

  // 栅格布局表单组件不做校验
  if (component.type == 'grid') {
    required = false;
  }

  if (component.valueType) {
    if (component.valueType == 'listo') {
      type = 'array';
    } else {
      type = component.valueType;
    }
  }

  if (component.type == 'dynamic' || component.type == 'anvilDynamic') {
    const columns = component.children.column;
    columns.map((col) => {
      // 用于处理表格形式的字表单子项校验
      col.rules = generateFormRules(col, data && data[prop] && data[prop][index] ? data[prop][index] : undefined);
    });
  }

  const rules = [
    {
      // requiredFunc是否通过函数获取required值
      required: component.requiredFunc && data ? eval(component.requiredFunc)(data) : required,
      message: `请输入正确的${des}${component.label || '值'}`,
      trigger: 'blur',
      pattern: pattern,
      type
    },
    {
      required,
      message: `${component.label || '值'}不能只包含空格`,
      trigger: 'blur',
      pattern: spacePattern,
      type
    }
  ];

  console.log('当前规则', rules);
  return rules;
};

// 将所有涉及联动的组件显示模式置为false, 参数 columns 组件列表, compsNeedInit 需要重置的组件prop列表
export const initCompsRef = function (columns, compsNeedInit) {
  const comps = [];
  compsNeedInit.map((prop) => {
    findCompByPropWithoutChildren(comps, prop, columns);
  });
  comps.map((item) => {
    const { prop, display } = item;
    if (display) {
      item.display = false;
    }
  });
};

// 将当前选项联动的所有组件设置为显示,同时将其他组件对应的表单值删除
export const setCompsRefShow = function (columns, compsRef) {
  // 将本次需要显示的组件prop存储起来
  const needShowComps = [],
    resArr = [];
  compsRef.map((prop) => {
    findCompByPropWithoutChildren(needShowComps, prop, columns);
  });
  needShowComps.map((item) => {
    const { prop, valueType, display } = item;
    if (!display) {
      item.display = true;
    }
    resArr.push(prop);
    // 根据当前组件的valueType去初始化值。因为在avue中，动态增加表单数据时，所有类型都会被转化成字符串类型
    // 但是如果将组件抽离avue这个form会出现问题，暂时先回退
    // if (component && component[form] && !component[form][prop]) {
    //   component.$set(component[form], prop, initValueByType(valueType));
    // }
  });
  return resArr;
};

// 将所有涉及联动的组件禁用模式置为true, 参数 columns 组件列表, compsNeedInit 需要重置的组件prop列表
export const initDisabledCompsRef = function (columns, compsNeedInit) {
  const comps = [];
  compsNeedInit.map((prop) => {
    findCompByPropWithoutChildren(comps, prop, columns);
  });
  comps.map((item) => {
    const { prop, disabled } = item;
    if (!disabled) {
      item.disabled = true;
    }
  });
};

// 将当前选项联动的所有组件设置为可用
export const setCompsRefEnable = function (columns, compsRef) {
  // 将本次需要启用的组件prop存储起来
  const needEnableComps = [],
    resArr = [];
  compsRef.map((prop) => {
    findCompByPropWithoutChildren(needEnableComps, prop, columns);
  });
  needEnableComps.map((item) => {
    const { prop, valueType, disabled } = item;
    if (disabled) {
      item.disabled = false;
    }
    resArr.push(prop);
  });
  return resArr;
};

export const initValueByType = function (valueType) {
  if (valueType == 'string') {
    return '';
  } else if (valueType == 'number') {
    return 0;
  } else if (valueType == 'array') {
    return [];
  } else if (valueType == 'datetime') {
    return undefined;
  }
};

// 寻找所有涉及联动的组件
export const findCompsRef = function (columns) {
  const comps = [];
  columns.map((item) => {
    if (item.dicData && item.dicData.length) {
      const { dicData } = item;
      dicData.forEach((dict) => {
        if (dict.compsRef) {
          comps.push(...dict.compsRef);
        }
      });
    }
  });
  return [...new Set(comps)];
};

// 删除所有当前display为false的组件的prop值
export const deletePropNoRef = function (columns, formData) {
  columns.forEach((item) => {
    const { display, prop } = item;
    if (!display && formData[prop]) {
      delete formData[prop];
    }
  });
};

// 在编辑页面根据组件prop查询组件，查找的是全部组件，包含表格和子表单内部组件
export const findCompByProp = function (res, compProp, columns) {
  columns.map((column) => {
    const { children, prop, type } = column;
    if (prop == compProp) {
      res.push(column);
    }
    if (children) {
      findCompByProp(res, compProp, children.column);
    }
    if (type == 'grid') {
      column.rows.map((item) => {
        findCompByProp(res, compProp, item.column);
      });
    } else if (type == 'anvilTabs') {
      column.tabs.map((item) => {
        findCompByProp(res, compProp, item.column);
      });
    }
  });
};

// 在编辑页面根据组件prop查询组件，查找的不包含表格和子表单内部组件
export const findCompByPropWithoutChildren = function (res, compProp, columns) {
  columns.map((column) => {
    const { children, prop, type } = column;
    if (prop == compProp) {
      res.push(column);
    }
    if (type == 'grid') {
      column.rows.map((item) => {
        findCompByPropWithoutChildren(res, compProp, item.column);
      });
    } else if (type == 'anvilTabs') {
      column.tabs.map((item) => {
        findCompByPropWithoutChildren(res, compProp, item.column);
      });
    }
  });
};

// 在编辑页面根据组件类型查询组件，查找的是全部组件，包含表格和子表单内部组件
export const findCompByType = function (res, compType, columns) {
  columns.map((column) => {
    const { children, type } = column;
    if (type == compType) {
      res.push(column);
    }
    if (children) {
      findCompByType(res, compType, children.column);
    }
    if (type == 'grid') {
      column.rows.map((item) => {
        findCompByType(res, compType, item.column);
      });
    } else if (type == 'anvilTabs') {
      column.tabs.map((item) => {
        findCompByType(res, compType, item.column);
      });
    }
  });
};

// 在预览/实际页面根据组件prop查询组件，查找的是全部组件，包含表格和子表单内部组件
export const findCompByPropInPreview = function (res, compProp, option) {
  if (option.column && option.column.length) {
    option.column.map((col) => {
      const { type, prop } = col;
      if (prop == compProp) {
        res.push(col);
      }
      if (col.children) {
        findCompByPropInPreview(res, compProp, col.children);
      } else if (type == 'grid') {
        col.rows.map((item) => {
          findCompByPropInPreview(res, compProp, item);
        });
      } else if (type == 'anvilTabs') {
        col.tabs.map((item) => {
          findCompByPropInPreview(res, compProp, item);
        });
      }
    });
  }

  if (option.group && option.group.length) {
    option.group.map((group) => {
      findCompByPropInPreview(res, compProp, group);
    });
  }
};

// 处理平台上传接口的返回值（旧）
export const getCustomUploadTrans = function (data) {
  const { storageId, fileType, url, fileName, storageType } = data;
  let resObj = {};
  if (storageType == 'local' || storageType == 'ftp') {
    const myUrl = location.origin + import.meta.env.VITE_APP_BASE_API + '/custom' + url;
    resObj = {
      storageId,
      fileName,
      url: myUrl,
      fileType,
      storageType,
      type: fileType
    };
  } else if (storageType == 'fdfs') {
    resObj = {
      storageId,
      fileName,
      url,
      fileType,
      storageType,
      type: fileType
    };
  }

  return resObj;
};

// 处理平台上传接口的返回值（新）
export const getZfsUploadTrans = function (data, isFileId) {
  const { storageId, fileOriginalName, fileExtName, fileId, fileUrl } = data;
  let url = '';
  if (fileUrl) {
    url = fileUrl;
  } else if (isFileId) {
    url = generateFileUrlByFileId(fileId);
  } else {
    url = generateFileUrl(storageId);
  }

  return {
    fileId,
    storageId,
    fileName: fileOriginalName,
    fileType: fileExtName,
    type: fileExtName,
    url
  };
};

// 根据storageId拼接文件地址
export const generateFileUrl = function (storageId) {
  return location.origin + import.meta.env.VITE_APP_BASE_API + '/zfs/view/' + storageId;
};

// 根据fileId拼接文件地址
export const generateFileUrlByFileId = function (fileId) {
  return location.origin + import.meta.env.VITE_APP_BASE_API + `/zfs/download?fileId=${fileId}&viewFlag=true`;
};

// 处理特殊符号转义处理
export const specialSignTrans = function (data) {
  const signs = [
    {
      oldSign: '&gt;',
      newSign: '>'
    },
    {
      oldSign: '&lt;',
      newSign: '<'
    }
  ];
  let res = data;
  signs.map((sign) => {
    const { oldSign, newSign } = sign;
    res = res.replaceAll(oldSign, newSign);
  });
  return res;
};

// 自定义的第三方api调用处理
export const customApiExecute = async function (config, extCfg) {
  const { url, params, callback, failCallback, isDownload } = config;
  console.log('正在执行customApiExecute');
  try {
    // 尝试将下载替换
    if (isDownload) {
      downloadUrl('/conn/api/download', { apiId: url, reqBodyBase64: Base64.encode(JSON.stringify(params)) });
      return;
    }
    const res = await executeApi({
      // 这里必须要传apiId
      apiId: url,
      reqBodyBase64: Base64.encode(JSON.stringify(params))
    });
    if (res && res.code == '200') {
      const resObj = res.data ? JSON.parse(res.data) : {};
      // 消息使用低代码接口返回的消息
      resObj.msg = res.msg;
      if (callback && typeof callback == 'function') {
        callback(resObj);
      }
    }
  } catch (e) {
    console.log('customApiExecute error!', e);
    if (failCallback && typeof failCallback == 'function') {
      failCallback(e);
    }
  }
};

// 模型接口调用处理
export const modelApiExecute = async function (config, extCfg) {
  const { url, headers, params, callback, failCallback, isDownload } = config;
  console.log('正在执行modelApiExecute', url, headers, params, callback);
  // 上传接口单独处理
  if (isDownload) {
    // downloadUrl默认会拼上base_api,所以要把url中的base_api去掉
    downloadUrl(url.replace(import.meta.env.VITE_APP_BASE_API, ''), params);
    return;
  }
  return ajax({
    url,
    method: 'post',
    headers,
    data: params,
    extCfg
  })
    .then((res) => {
      if (res && res.code == '200') {
        if (callback && typeof callback == 'function') {
          callback(res);
        }
      }
    })
    .catch((e) => {
      console.log('modelApiExecute error!', e);
      if (failCallback && typeof failCallback == 'function') {
        failCallback(e);
      }
    });
};

// 本地接口调用处理
export const localApiExecute = async function (config, extCfg) {
  const { url, method, contentType, headers, params, callback, failCallback, isDownload } = config;
  console.log('正在执行localApiExecute', url, method, contentType, headers, params, callback);
  // 上传接口单独处理
  if (isDownload) {
    // downloadUrl默认会拼上base_api,所以要把url中的base_api去掉
    downloadUrl(url.replace(import.meta.env.VITE_APP_BASE_API, ''), params);
    return;
  }
  // 不同的请求体类型分别处理
  if (contentType == 'rawJson') {
    return localAjaxByJson({
      url,
      method: method ? method : 'post',
      headers,
      data: method == 'get' ? undefined : params,
      params: method == 'get' ? params : undefined,
      extCfg
    })
      .then((res) => {
        if (res && res.code == '200') {
          if (callback && typeof callback == 'function') {
            callback(res);
          }
        }
      })
      .catch((e) => {
        console.log('localApiExecute error!', e);
        if (failCallback && typeof failCallback == 'function') {
          failCallback(e);
        }
      });
  } else {
    return localAjax({
      url,
      method: method ?? 'post',
      headers,
      data: method == 'get' ? undefined : params,
      params: method == 'get' ? params : undefined,
      extCfg
    })
      .then((res) => {
        if (res && res.code == '200') {
          if (callback && typeof callback == 'function') {
            callback(res);
          }
        }
      })
      .catch((e) => {
        console.log('localApiExecute error!', e);
        if (failCallback && typeof failCallback == 'function') {
          failCallback(e);
        }
      });
  }
};

// 对接口获取的组件json对象进行处理，主要是铺平并获取容器中的可以支持调用的组件列表,不包含子表单和表格内部子组件
export const getJsonCallableCompList = (option) => {
  let arr = [];

  if (option.column) {
    option.column.map((col) => {
      arr.push(col);
      if (col.type == 'grid') {
        col.rows.map((childOption) => {
          const list = getJsonCallableCompList(childOption);
          arr.push(...list);
        });
      } else if (col.type == 'anvilTabs') {
        col.tabs.map((childOption) => {
          const list = getJsonCallableCompList(childOption);
          arr.push(...list);
        });
      }
    });
  }

  if (option.group) {
    option.group.map((group) => {
      const list = getJsonCallableCompList(group);
      arr.push(...list);
    });
  }
  return arr;
};

// 获取并铺平所有可以支持调用的组件列表，包括子表单和表格内的所有组件
export const getJsonCallableCompListWithChildren = (option) => {
  let arr = [];

  if (option.column) {
    option.column.map((col) => {
      arr.push(col);
      if (col.children) {
        const list = getJsonCallableCompListWithChildren(col.children);
        arr.push(...list);
      } else if (col.type == 'grid') {
        col.rows.map((childOption) => {
          const list = getJsonCallableCompListWithChildren(childOption);
          arr.push(...list);
        });
      } else if (col.type == 'anvilTabs') {
        col.tabs.map((childOption) => {
          const list = getJsonCallableCompListWithChildren(childOption);
          arr.push(...list);
        });
      }
    });
  }

  if (option.group) {
    option.group.map((group) => {
      const list = getJsonCallableCompListWithChildren(group);
      arr.push(...list);
    });
  }
  return arr;
};

// 对编辑器的组件对象进行处理，主要是铺平并获取容器中的可以支持调用的组件列表,不包含子表单和表格内部子组件
export const getCallableCompList = (option) => {
  if (option) {
    const { column } = option;
    const res = [];

    column.map((col) => {
      const { type } = col;
      res.push(col);
      if (type == 'group') {
        res.push(...getCallableCompList(col.children));
      } else if (type == 'grid') {
        col.rows.map((item) => {
          res.push(...getCallableCompList(item));
        });
      } else if (type == 'anvilTabs') {
        col.tabs.map((item) => {
          res.push(...getCallableCompList(item));
        });
      }
    });
    return res;
  } else {
    return [];
  }
};

// 获取并铺平所有可以支持调用的组件列表，包括子表单和表格内的所有组件
export const getCallableCompListWithChildren = (option) => {
  if (option) {
    const { column } = option;
    const res = [];

    column.map((col) => {
      const { type, children } = col;
      res.push(col);
      if (children) {
        res.push(...getCallableCompList(children));
      } else if (type == 'grid') {
        col.rows.map((item) => {
          res.push(...getCallableCompList(item));
        });
      } else if (type == 'anvilTabs') {
        col.tabs.map((item) => {
          res.push(...getCallableCompList(item));
        });
      }
    });
    return res;
  } else {
    return [];
  }
};

// 定义一个执行器函数，接受一个函数数组,函数中包含异步与同步方法，完成链式调用
export const executeFunctionsInOrder = (settingArray, data) => {
  // 使用reduce函数来构建Promise链

  const anvilCodeStore = useAnvilCodeStore();
  settingArray.reduce((promise, setting) => {
    // 返回一个新的Promise，该Promise会在当前函数执行完后解析

    return promise.then(() => {
      try {
        // 如果当前函数返回一个Promise，则等待其完成
        const { pageId, type, component, event, jsonPath } = setting;

        const instance = anvilCodeStore.getInstance(pageId, type, component);

        let params = data;

        if (jsonPath) {
          params = jp.query(data, jsonPath)[0];
        }

        console.log('调用了', instance, '实例的' + event + '方法' + '参数为', JSON.stringify(params));
        let result = null;
        if (!instance) {
          console.error('没有找到' + component + '实例的' + event + '方法');
          return Promise.resolve();
        }

        if (Object.prototype.toString.call(instance) == '[object Array]') {
          result = Promise.all(instance.map((i) => i[event](params)));
        } else {
          result = instance[event](params);
        }

        if (result && typeof result.then === 'function') {
          return result;
        }
        // 如果当前函数没有返回Promise，直接返回一个已解析的Promise
        return Promise.resolve();
      } catch (e) {
        ElMessage.error(e.message);
        return Promise.reject(e);
      }
    });
  }, Promise.resolve());
};

// 根据日期时间默认值类型生成默认值
export const handleDefaultDateTime = (column) => {
  const { defaultDateTime, valueFormat, customDateTimeFunc } = column;
  return generateDefaultDateTime(defaultDateTime, valueFormat, customDateTimeFunc);
};

export const handleDefaultDateTimeRange = (column) => {
  const { defaultStartTime, customStartTimeFunc, defaultEndTime, customEndTimeFunc, valueFormatStr } = column;
  let startTime = undefined,
    endTime = undefined;
  if (defaultStartTime) {
    startTime = generateDefaultDateTime(defaultStartTime, valueFormatStr, customStartTimeFunc);
  }
  if (defaultEndTime) {
    endTime = generateDefaultDateTime(defaultEndTime, valueFormatStr, customEndTimeFunc);
  }
  return [startTime, endTime];
};

const generateDefaultDateTime = (type, format, func) => {
  try {
    switch (type) {
      case 'now':
        return dayjs().format(format);
      case 'yesterday':
        return dayjs().subtract(1, 'day').startOf('D').format(format);
      case 'tomorrow':
        return dayjs().add(1, 'day').startOf('D').format(format);
      case 'lastmonth':
        return dayjs().subtract(1, 'month').startOf('M').format(format);
      case 'nextmonth':
        return dayjs().add(1, 'month').startOf('M').format(format);
      case '6hpre':
        return dayjs().subtract(6, 'hour').startOf('h').format(format);
      case '1hpre':
        return dayjs().subtract(1, 'hour').startOf('h').format(format);
      case '6hnext':
        return dayjs().add(6, 'hour').startOf('h').format(format);
      case '1hnext':
        return dayjs().add(1, 'hour').startOf('h').format(format);
      case 'custom':
        return eval(func)(dayjs);
    }
  } catch (e) {
    console.log('generateDefaultDateTime error!', e);
  }
};

// 序列号组件在组件调用前钩子中需要执行的方法
export const handleGetSerialNumber = async (columns, formData) => {
  try {
    const promises = [];
    columns.map((col) => {
      const { type } = col;
      // 栅格布局特殊处理
      if (type == 'grid') {
        col.rows.map((row) => {
          row.column.map((item) => {
            promises.push(getSerialNumberValue(item, formData));
          });
        });
      } else {
        promises.push(getSerialNumberValue(col, formData));
      }
    });
    await Promise.all(promises);
  } catch (e) {
    console.log('handleGetSerialNumber error!', e);
  }
};

const getSerialNumberValue = (col, formData) => {
  const { prop, type, sequenceCode, hookBefore, hookAfter } = col;
  // 满足类型，同时表单值为空，则调用接口获取值
  if (type == 'serialNumber' && sequenceCode && !formData[prop]) {
    let params = sequenceCode;
    const anvilCodeStore = useAnvilCodeStore();
    // 获取当前表单实例
    const { instance } = anvilCodeStore.getCurPageForm;
    if (hookBefore) {
      params = instance[hookBefore](params);
    }
    const promise = searchSequenceValue(params).then((res) => {
      let data = res;
      if (hookAfter) {
        data = instance[hookAfter](data);
      }
      formData[prop] = data.data;
    });
    return promise;
  }
};

// 根据组件类型生成ref
export const generateRef = (item) => {
  switch (item.type) {
    case 'anvilDynamic':
      return `dynamicItem${item.prop}`;
    case 'grid':
      return `gridItem${item.prop}`;
    case 'anvilTabs':
      return `tabsItem${item.prop}`;
    default:
      return undefined;
  }
};

// 对传入的option进行处理，主要处理template模板组件
export const handleOptionTrans = (data) => {
  console.log('正在处理template');
  if (data && data.column) {
    data.column.map((col, index) => {
      const { type } = col;
      if (type == 'template') {
        const column = getTemplateCompColumns(col);
        data.column.splice(index, 1, ...column);
      }
    });
  }

  if (data && data.group) {
    data.group.map((group, index) => {
      group.column.map((col, idx) => {
        const { type } = col;
        if (type == 'template') {
          const column = getTemplateCompColumns(col);
          data.group[index].column.splice(idx, 1, ...column);
        }
      });
    });
  }
};

// 根据模板组件json得到组件渲染数组
const getTemplateCompColumns = (data) => {
  try {
    const { content } = data;
    const contentObj = JSON.parse(content);
    const { column } = contentObj;
    return column;
  } catch (e) {
    console.log('getTemplateCompColumns error!', e);
    return [];
  }
};

// 获取当前表单下所有调用的参数，包括行数据
export const getFormDataWithScope = (that) => {
  const anvilCodeStore = useAnvilCodeStore();
  const pageId = that.pageId || that.$attrs.pageId;
  const defaultParams = anvilCodeStore.getDefaultParams(pageId, that);
  let formData = {
    ...defaultParams
  };

  if (that.scopeRow && that.scopeRow.row) {
    // 携带row对象与row内属性
    formData = {
      ...formData,
      ...that.scopeRow,
      ...that.scopeRow.row
    };
  } else if (that.$attrs && that.$attrs.scopeRow && that.$attrs.scopeRow.row) {
    // 携带row对象与row内属性
    formData = {
      ...formData,
      ...that.$attrs.scopeRow,
      ...that.$attrs.scopeRow.row
    };
  }
  console.log('当前携带行内数据，总参数为', formData);

  return cloneDeep(formData);
};

// 根据参数设置获取合并完整的参数对象
export const getParamsWithMerge = (that, option) => {
  if (!option || typeof option !== 'object') {
    return {};
  }
  const { contantParams, compParams, withFormData } = option;
  const anvilCodeStore = useAnvilCodeStore();

  let Params = {};
  if (contantParams && contantParams.length) {
    contantParams.map((p) => {
      const { key, value } = p;
      Params[key] = value;
    });
  }

  if (compParams && compParams.length) {
    compParams.map((p) => {
      try {
        const { key, value } = p;
        const { pageId, type, component, event, jsonPath } = value;
        const instance = anvilCodeStore.getInstance(pageId, type, component);
        let compData = instance[event]();
        if (jsonPath && compData) {
          compData = jp.query(compData, jsonPath)[0];
        }
        Params[key] = compData;
      } catch (e) {
        console.log('getParamsWithMerge error!', e);
      }
    });
  }

  // 兼容老数据，如果withFormData为false，则不合并表单数据
  if (withFormData !== false) {
    const data = getFormDataWithScope(that);
    Params = Object.assign({}, data, Params);
  }

  return Params;
};

// 定义一个执行器函数，接受一个函数数组,函数中包含异步与同步方法，完成链式调用
// compParams 参数 functionsArray 执行队列 isParamsSetting 是否为配置型参数
export const executeFunctionsInOrderByParamsSetting = (that, compParams, functionsArray, isParamsSetting) => {
  console.log('当前实例为', that);
  // 使用reduce函数来构建Promise链
  functionsArray.reduce((promise, comp) => {
    // 返回一个新的Promise，该Promise会在当前函数执行完后解析
    return promise.then(() => {
      try {
        const anvilCodeStore = useAnvilCodeStore();
        // 如果当前函数返回一个Promise，则等待其完成
        const { pageId, type, component, event, jsonPath } = comp;
        const instance = anvilCodeStore.getInstance(pageId, type, component);
        let params = undefined;

        if (compParams) {
          if (isParamsSetting) {
            // 配置型参数需要解析,然后执行钩子
            params = getParamsWithMerge(that, compParams);
            const { hookBefore } = compParams;
            const { instance: formInstance } = anvilCodeStore.getPageForm(that.pageId || that.$attrs.pageId);
            if (hookBefore) {
              params = formInstance[hookBefore](params);
            }
          } else {
            // 静态参数直接赋值
            params = compParams;
          }
        }

        if (params && jsonPath) {
          params = jp.query(params, jsonPath)[0];
        }
        console.log('调用了', instance, '实例的' + event + '方法' + '参数为', JSON.stringify(params));
        let result = null;
        if (!instance) {
          console.error('没有找到' + component + '实例的' + event + '方法');
          return Promise.resolve();
        }

        if (Object.prototype.toString.call(instance) == '[object Array]') {
          result = Promise.all(instance.map((i) => i[event](params)));
        } else {
          result = instance[event](params);
        }
        if (result && typeof result.then === 'function') {
          console.log('result', result);
          return result;
        }
        // 如果当前函数没有返回Promise，直接返回一个已解析的Promise
        return Promise.resolve();
      } catch (e) {
        ElMessage.error(e.message);
        return Promise.reject(e);
      }
    });
  }, Promise.resolve());
};

// 强制刷新父页面
export const forceUpdateParentForm = (pageId) => {
  try {
    // 先找到当前页面实例
    const anvilCodeStore = useAnvilCodeStore();
    const form = anvilCodeStore.getPageForm(pageId);
    console.log('当前表单instance', form.instance);
    // 找到表单的父级页面，然后调用强制更新表单的方法
    const parent = form.instance.$parent;
    if (parent && parent.updateFormRender) {
      console.log('正在执行表单初始化');
      parent.updateFormRender();
    }
  } catch (e) {
    this.msgError('forceUpdateParentForm Error!', e);
  }
};

// 查找是否存在开启的显隐规则表达式
export const isExistDisplayRule = (option) => {
  if (!option.displayRules || !option.displayRules.length) {
    return false;
  }
  const RulesActive = option.displayRules.filter((rule) => rule.enable);
  return RulesActive.length > 0;
};

// 解析获取显隐规则表达式
export const getDisplayRule = (rule) => {
  const { logicalRelation, isGroup, children, field, condition, value } = rule;
  if (!isGroup) {
    if (condition == 'RE') {
      return `(new RegExp('${value}').test(${field}))`;
    } else {
      if (condition == 'NU') {
        return `(${field} == undefined || ${field} == null || ${field} == '')`;
      } else if (condition == 'NN') {
        return `(${field} != undefined && ${field} != null && ${field} != '')`;
      }
      // 区分数字、布尔值比较还是文本比较
      else if (condition == 'EQ' || condition == 'NE') {
        return `(${field} ${condition} '${value}')`.replaceAll('EQ', '==').replaceAll('NE', '!=');
      } else {
        return `(${field} ${condition} ${value})`.replaceAll('GT', '>').replaceAll('LT', '<').replaceAll('GE', '>=').replaceAll('LE', '<=').replaceAll(' ', '');
      }
    }
  } else {
    if (children && children.length) {
      const childrenRule = children.map((item) => {
        return getDisplayRule(item);
      });
      switch (logicalRelation) {
        case 'and':
          return `(${childrenRule.join('&&')})`;
        case 'or':
          return `(${childrenRule.join('||')})`;
        case 'not':
          return `!(${childrenRule.join('&&')})`;
      }
    } else {
      return '';
    }
  }
};

// 实现自定义的上传回调功能
export const customUploadByApi = (that, file, setting) => {
  try {
    const { customCallback, url, hookBefore, hookAfter, headers, params } = setting;
    const anvilCodeStore = useAnvilCodeStore();
    // 获取当前表单实例
    const { instance } = anvilCodeStore.getPageForm(that.pageId);

    // 回调方法， 执行后置钩子
    const callback = (res) => {
      try {
        let finalRes = res;
        if (hookAfter) {
          finalRes = instance[hookAfter](res);
        }
        executeFunctionsInOrder(customCallback, finalRes);
        console.log('调用成功！', res);
      } catch (e) {
        console.log('customUploadByApi callback error!', e);
      }
    };

    let Header = {};

    if (headers) {
      headers.map((item) => {
        Header[item.key] = item.value;
      });
    }

    const data = getParamsWithMerge(that, params);

    let Param = {
      apiId: url,
      file,
      ...data
    };

    // 执行前置钩子
    if (hookBefore) {
      Param = instance[hookBefore](Param);
    }

    return uploadApi(Header, Param).then((res) => {
      callback(res);
    });
  } catch (e) {
    console.log('customUploadByApi error!', e);
  }
};

// 根据classNames动态创建样式文件
export const generateStyleSheet = (classes) => {
  if (classes && classes.length) {
    classes.forEach((styleClass) => {
      const styleElement = document.createElement('style');
      styleElement.type = 'text/css';
      const styleString = `.${styleClass.className} { ${styleClass.classStyle} }`;
      styleElement.appendChild(document.createTextNode(styleString));
      document.head.appendChild(styleElement);
    });
  }
};

const randomLetter = (len) => {
  len = len || 32;
  const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  const maxPos = $chars.length;
  let pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
};

// 生成合法的组件uuid字符串，首字母必须不为数字
export const generateValidUuid = () => {
  let uuid = randomString();
  const RegExp = /^[0-9]/;
  if (uuid && RegExp.test(uuid)) {
    const propChars = Array.from(uuid);
    propChars[0] = randomLetter(1);
    uuid = propChars.join('');
  }
  return uuid;
};
